package com.bitcat.base.widget.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.WindowManager
import com.bitcat.base.R
import com.bitcat.base.databinding.LayoutBaseDialogLoadingBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel

class LoadingDialog private constructor(context: Context,val title: String,val cancelable: Boolean,val cancelOutside: Boolean,val coroutineScope: CoroutineScope?): Dialog(context,android.R.style.Theme_Material_Dialog) {

    private val binding: LayoutBaseDialogLoadingBinding by lazy {
        LayoutBaseDialogLoadingBinding.inflate(LayoutInflater.from(context))
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        //设置标题
        binding.loadingTips.text = title

        setCancelable(cancelable)
        setCanceledOnTouchOutside(cancelOutside)

        window?.setBackgroundDrawableResource(android.R.color.transparent)

        //屏幕宽度的80%
        val windowWith = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.width
        window?.setLayout(

//            (windowWith * 0.8).toInt(),
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
        )

        //监听弹窗关闭
        setOnCancelListener {
            coroutineScope?.cancel()
        }
    }




    class Builder(val context: Context) {
        private var title: String = "请求网络中..."
        private var cancelable: Boolean = true
        private var cancelOutside: Boolean = true

        private var coroutineScope: CoroutineScope? = null


        fun setTitle(title: String): Builder {
            this.title = title
            return this
        }

        fun setCancelable( cancelable: Boolean): Builder{
            this.cancelable = cancelable
            return this
        }


        fun setCancelOutside( cancelOutside: Boolean): Builder{
           this.cancelOutside = cancelOutside
            return this
        }

        fun setCoroutineScope(coroutineScope: CoroutineScope?): Builder{
            this.coroutineScope = coroutineScope
            return this
        }

        fun build(): LoadingDialog {
            return LoadingDialog(context,title,cancelable,cancelOutside,coroutineScope)
        }
    }
}